import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCInsert {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);

        // 1. 创建并初始化一个数据源
        DataSource dataSource = new MysqlDataSource(); // 向上转型
        // 向下转型  setUrl 是子类才有的方法
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        // 2. 和数据库服务器建立连接
        Connection connection = dataSource.getConnection();

        // 3. 构造sql语句

        /*
        String sql = "delete from student where id = 2 limit 1";
        PreparedStatement statement = connection.prepareStatement(sql);
         */

        /*
        System.out.println("请输入id: ");
        int id = scanner.nextInt();
        System.out.println("请输入name: ");
        String name = scanner.next();
        String sql = "insert into student values (" + id + ",'" + name + "')";
        PreparedStatement statement = connection.prepareStatement(sql);
         */

        String sql = "insert into student values (?,?)";// 占位符
        System.out.println("请输入id: ");
        int id = scanner.nextInt();
        System.out.println("请输入name: ");
        String name = scanner.next();
        // 预编译sql语句 减少服务器的压力
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.setString(2,name);

        // 4. 执行sql语句
        int ret = statement.executeUpdate();
        System.out.println("ret = " + ret);

        // 5. 释放必要的资源
        // 后创建的先释放
        statement.close();
        connection.close();
    }
}
